package cn.iocoder.yudao.module.cook.service.cailiao;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.cook.controller.admin.cailiao.vo.*;
import cn.iocoder.yudao.module.cook.dal.dataobject.cailiao.CailiaoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.cook.dal.mysql.cailiao.CailiaoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cook.enums.ErrorCodeConstants.*;

/**
 * 食谱材料 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CailiaoServiceImpl implements CailiaoService {

    @Resource
    private CailiaoMapper cailiaoMapper;

    @Override
    public Long createCailiao(CailiaoSaveReqVO createReqVO) {
        // 插入
        CailiaoDO cailiao = BeanUtils.toBean(createReqVO, CailiaoDO.class);
        cailiaoMapper.insert(cailiao);
        // 返回
        return cailiao.getId();
    }

    @Override
    public void updateCailiao(CailiaoSaveReqVO updateReqVO) {
        // 校验存在
        validateCailiaoExists(updateReqVO.getId());
        // 更新
        CailiaoDO updateObj = BeanUtils.toBean(updateReqVO, CailiaoDO.class);
        cailiaoMapper.updateById(updateObj);
    }

    @Override
    public void deleteCailiao(Long id) {
        // 校验存在
        validateCailiaoExists(id);
        // 删除
        cailiaoMapper.deleteById(id);
    }

    private void validateCailiaoExists(Long id) {
        if (cailiaoMapper.selectById(id) == null) {
            throw exception(CAILIAO_NOT_EXISTS);
        }
    }

    @Override
    public CailiaoDO getCailiao(Long id) {
        return cailiaoMapper.selectById(id);
    }

    @Override
    public PageResult<CailiaoDO> getCailiaoPage(CailiaoPageReqVO pageReqVO) {
        return cailiaoMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CailiaoDO> getCailiaoList(CailiaoListReqVO listReqVO) {
        List<CailiaoDO> list = cailiaoMapper.selectList(listReqVO);
        list.sort(Comparator.comparing(CailiaoDO::getSort));
        return list;
    }
}